<template>
  <div class="content flex-col">
    <div class="content_nav flex-row">
      <CgsNav :data="categoryList"
              :default-active="activeName"
              @itemChange="getList"
      >
        <template slot="buttons">
          <div class="content-buttons flex-row">
<!--            <CgsButton v-show="userAuthority.IMPORT" @click.stop="handleImport">-->
<!--              <span class="button-icon import"></span>-->
<!--              导入-->
<!--            </CgsButton>-->
            <CgsButton  v-show="userAuthority.ADD_APP" style="width: 120px" @click="handleAdd">
              <span class="button-icon add"></span>
              添加场景
            </CgsButton>
            <CgsSwitch active-text="卡片"
                       inactive-text="列表"
                       v-model="displayModel"
            />
          </div>
        </template>
      </CgsNav>
    </div>
    <div v-if="displayModel" class="content-card-list flex-row">
      <div class="content-card-item"
           v-for="(app, index) in appList"
           :key="app.id">
        <CgsCard :app-data="app"
                 :show-mask="app.appAuths.CONFIG_PROJECT"
                 @authority="handleAuthority(app, index)"
                 @delete-app="handleDeleteApp(app, index)"
                 @modify="handleModifyApp(app, index)"
                 @preview="handlePreview(app, index)"
                 @export-app="handleExport(app, index)"
                 @editor="handleEditorApp(app, index)"
        >
          <template slot="title">
            {{app.title}}
          </template>
        </CgsCard>
      </div>
    </div>
    <div v-if="!displayModel" class="content_list flex-col">
      <div class="content_list-item"
           style="width: 100%"
           v-for="(app, index) in appList"
           :key="app.id">
        <CgsList :app-data="app"
                 :show-mask="app.appAuths.CONFIG_PROJECT"
                 @authority="handleAuthority(app, index)"
                 @delete-app="handleDeleteApp(app, index)"
                 @modify="handleModifyApp(app, index)"
                 @preview="handlePreview(app, index)"
                 @export-app="handleExport(app, index)"
                 @editor="handleEditorApp(app, index)"
        >
          <template slot="title">
            {{app.title}}
          </template>
        </CgsList>
      </div>
    </div>
    <div class="content_floor">
      <CgsPagination
              :total="page.total"
              :page-size="page.pageSize"
              :current-page="page.currentPage"
              @page-size-change="pageSizeChange"
              @page-change="pageChange"
      />
    </div>

    <el-dialog :title="submitModel === 'add'? '一 添加场景 一': '一 修改信息 一'"
               :visible.sync="showAddScene"
               width="700px"
               center>
      <el-form label-position="left" label-width="120px"
               :model="formAddScene"
               :rules="formAddRules" ref="formAddScene"
      >
        <el-form-item label="分组:" prop="category">
          <el-select class="cgs-select"
                     v-model="formAddScene.category"
                     placeholder="选择分组"
          >
            <el-option v-for="category in categoryList"
                       :key="category.index"
                       :value="category.index"
                       :label="category.title"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="场景名称:" prop="title">
          <el-input class="cgs-input"
                    v-model="formAddScene.title"
                    placeholder="请输入场景名称"/>
        </el-form-item>
        <el-form-item label="密码:">
          <el-input class="cgs-input"
                    v-model="formAddScene.password"
                    placeholder="请输入密码"/>
        </el-form-item>
        <el-form-item label="发布状态:">
          <CgsSwitch active-text="发布"
                     v-model="formAddScene.status"
                     inactive-text="未发布" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
        <el-button @click="showAddScene = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import CgsCard from "../components/CgsCard";
  import CgsNav from "../components/CgsNav";
  import CgsButton from "../components/CgsButton";
  import CgsSwitch from "../components/CgsSwitch";
  import CgsPagination from "../components/CgsPagination";
  import CgsList from "../components/CgsList";

  import {addObj, delObj, getCategory, getList, getObj, updateObj, uploadZip} from '@/api/visual';
  import {getTenantInfo, getUserAuthority, setUserAuthority} from "@/util/auth";
  import {getUserInfo} from "@/api/user";

  // import {url} from "@/config";
export default {
  name: "largeScene",
  components: {
    CgsList,
    CgsCard,
    CgsNav,
    CgsButton,
    CgsSwitch,
    CgsPagination
  },
  data(){
    return {
      userAuthority: {},
      page: {
        total: 200,
        pageSize: 10,
        currentPage: 1
      },
      categoryList: [],
      submitModel: "add",
      activeName: 'default',
      formAddScene: {
        id: '',
        category: '',
        title: '',
        password: '',
        status: false,
        width: 1920,
        height: 1080
      },
      formAddRules: {
        category: [
          { required: true, message: '请选择分组', trigger: 'change' }
        ],
        title: [
          { required: true, message: '请输入场景名称', trigger: 'blur' }
        ],
      },
      displayModel: true,
      appList: [],
      showAddScene: false
    }
  },
  computed:{
  },
  methods: {
    handleAdd() {
        this.submitModel = 'add';
        this.showAddScene = true
        this.formAddScene = {
            id: '',
            category: '',
            title: '',
            password: '',
            status: false,
            width: 1920,
            height: 1080
        }
        this.formAddScene.category = this.activeName
    },
    getList (category) {
      const loading = this.$loading({
        lock: true,
        text: '正在加载中，请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      this.appList = [];
      this.activeName = category;
      getList({
        Category: category || (this.activeName === "default" ? "" : this.activeName),
        Current: this.page.currentPage,
        Size: this.page.pageSize,
        VisualType: "Visual"
      }).then(res => {
        loading.close();
        const data = res.data.data;
        this.page.total = data.total;
        let list = data.records;
        let appAuths = getUserAuthority().appAuths;

        for (let i = 0; i < list.length; i++) {
          list[i]["appAuths"] = {}
          if(appAuths[list[i].id]){
            for (let j = 0; j < appAuths[list[i].id].length; j++) {
              list[i]["appAuths"][appAuths[list[i].id][j]] = !this.tenantInfo.account.timeout;

              //阻止导出
              if(appAuths[list[i].id][j] === 'EXPORT'){
                list[i]["appAuths"][appAuths[list[i].id][j]] = false;
              }
            }
          }
        }
        // console.log(list);
        this.appList = list;
        // console.log(this.appList)
      })
    },
    handleImport() {
      let self = this;
      var inputObj = document.createElement('input')
      inputObj.setAttribute('id','importZip');
      inputObj.setAttribute('type','file');
      inputObj.setAttribute('name','importZip');
      inputObj.setAttribute("style",'visibility:hidden');
      document.body.appendChild(inputObj);
      inputObj.click();
      inputObj.addEventListener('change', e => {
        if(e.target.files[0]){
          //创建formdata对象
          let formdata = new FormData();
          formdata.append("file", e.target.files[0]);

          formdata.append("category", self.activeName);

          uploadZip(formdata).then(res => {
            if(res.data.code === 200){
              this.$message.success("导入成功！")
              this.updateAuthority();
            }else {
              this.$message.error("导入失败！")
            }
          });
        }
      });
    },
    handleSubmit() {
      this.$refs.formAddScene.validate((valid) => {
        if (valid) {
          let {status} = this.formAddScene
          status = status ? 1: 0
          if (this.submitModel === 'add') {
            addObj(Object.assign(this.formAddScene, {
                status,
                isPortal: true,
                VisualType: "Visual"
            })).then(res => {
              if(res.data && res.data.success){
                this.updateAuthority();
                this.$message.success('添加成功');
              } else {
                this.$message.error('添加失败');
              }
              this.showAddScene = false
            })
          } else {
            updateObj(Object.assign(this.formAddScene, {
              status,
              isPortal: true,
              VisualType: "Visual"
            })).then(() => {
              this.showAddScene = false;
              this.$message.success('修改成功');
              this.getList(this.activeName);
            })
          }
        } else {
          return false;
        }
      });
    },
    handleAuthority(item) {
      this.$router.push({name: 'authority', params: {visualType: 'Visual', appId: item.id}})
    },
    handleDeleteApp(item, index) {
      this.$confirm('是否确认永久删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        /*if (this.vaildData(index)) {
          this.$message.error('例子模板不允许修改')
          return false;
        }*/
        delObj({
            ID: item.id,
            VisualType: "Visual"
          }).then(() => {
          this.appList.splice(index, 1);
          this.$message.success('删除成功')
        })
      }).catch(() => {

      });
    },
    handleModifyApp(item) {
      this.submitModel = 'update';
      this.showAddScene = true;
      this.formAddScene.status = item.status === 1
      this.formAddScene.category = item.category? item.category.toString() : "default"
      this.formAddScene.title = item.title
      this.formAddScene.id = item.id
    },
    handlePreview(item) {
      getObj({
          ID: item.id,
          VisualType: "Visual"
      }).then(res => {
        if (res.data.code === 200) {
          let config = res.data.data.config;
          var originHostName=window.location.hostname;
          var url= "";

          let visual = res.data.data.visual
          if (visual.projectID && visual.projectID !== "") {
            url = `//${originHostName}:20000/view.html?ProjId=${visual.projectID}&mode=preview`
          } else if (config.sceneUrl && config.sceneUrl !== "") {
            // url=config.sceneUrl.replace(/\/\/.*:/,"//"+originHostName+":");// 替换IP
            url=config.sceneUrl;// cesium 临时使用
          }
          window.open(url, '_blank');
        }
      })
    },
    handleExport(item) {
      this.$confirm('确定导出', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let url = "//localhost:2020/api/Cgs/Portal/Export?visualId=";
        url = url.replace("localhost", window.location.hostname)
        window.open(url + item.id + "&visualType=Visual");
      })
    },
    handleEditorApp(item) {
      let routeUrl = this.$router.resolve({
        path: '/build/' + item.id
      })
      window.open(routeUrl.href, '_blank');
    },
    pageSizeChange(value) {
      this.page.pageSize = value;
      this.getList(this.activeName);
    },
    pageChange(value) {
      this.page.currentPage = value;
      this.getList(this.activeName);
    },
    updateAuthority(){
      getUserInfo().then(infoRes => {
        if(infoRes.data && infoRes.data.success){
          setUserAuthority(infoRes.data.data);
          this.getList(this.activeName);
        }
      })
    },
  },
  created () {
    //获得分类列表
    getCategory({
        VisualType: 'Visual'
    }).then(res => {
      const data = res.data.data;
      // categoryKey
      this.categoryList = data.map(d => {return {...d, ...{title: d.categoryKey, index: d.categoryValue}}});
      this.categoryList.unshift({title: '默认', index: 'default'})
      this.activeName = 'default';
      this.formAddScene.category = (data[0] || {}).categoryValue;
      this.getList(this.activeName);
    })

    //
    let userAuth = getUserAuthority();
    this.tenantInfo = getTenantInfo();
    let authorities = userAuth["operatingAuthorities"];
    this.userAuthority = {};
    if(!authorities){
      authorities = [];
    }
    for (let i = 0; i < authorities.length; i++) {
      this.userAuthority[authorities[i]] = true;
    }
  },
}
</script>
